package edu.ucsb.cs176b.android;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.mime.content.*;

import android.graphics.drawable.Drawable;

public class NetworkUtil {
	
	public static Drawable getDrawableFromUrl(String url, String src_name){
		try {
			return Drawable.createFromStream(((InputStream)new URL(url).getContent()), src_name);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}  
	}
	

	public static String uploadPicture(String h, byte[] pic, String token, int cid) throws URISyntaxException, UnsupportedEncodingException{

		if(pic != null) { 

			URI host = new URI("http://" + h + "/upload");

			HttpClient client = new DefaultHttpClient(); 
			HttpPost httppost = new HttpPost(host);
			MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
			entity.addPart("image", new ByteArrayBody(pic,"image/jpeg", "th.jpg"));
			entity.addPart("cid", new StringBody( String.valueOf(cid) ) );
			entity.addPart("token", new StringBody(token));
			httppost.setEntity(entity);
	
	        try {
				HttpResponse response = client.execute(httppost);
	            HttpEntity resEntity = response.getEntity();
	            
	            if (resEntity != null) {
	                String result = "";
	                try{
	                    InputStream in = response.getEntity().getContent();
	                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	                    StringBuilder str = new StringBuilder();
	                    String line = null;
	                    while((line = reader.readLine()) != null){
	                        str.append(line + "\n");
	                    }
	                    in.close();
	                    result = str.toString();
	                }catch(Exception ex){
	                    result = "Error";
	                }
	                System.out.println(result);
	                return result;
	            }
	                   
			} catch (ClientProtocolException e) {
	
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
			}
		return null;
	}

	public static String getSringFromUrl(String url) {
		
		// Create a HTTP client
    	HttpClient httpclient = new DefaultHttpClient();
 
        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 
        
        // Execute the request
        HttpResponse response;
        try {
        	response = httpclient.execute(httpget);
            
            // Examine the response status
            
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            
            // If the response does not enclose an entity, there is no need
            // to worry about connection release  
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);
                
                // Closing the input stream will trigger connection release
                instream.close();
                
                return result; 
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return null;
	}

	/**
	* Convert a InputStream to a String
	* 
	* @param is the InputStream return from the HttpClient request
	* @return the result String from the conversion
	*/
	public static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		
		String line = null;
		try {
		    while ((line = reader.readLine()) != null) {
		        sb.append(line + "\n");
		    }
		} 
		catch (IOException e) {
		    e.printStackTrace();
		} 
		finally {
		    try {
		        is.close();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
		
		return sb.toString();
	}
	
}